<?php
namespace MyAdmin\Controller;

use Think\Controller;

class MsProductsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function ms_list(){
    $page = I("page", 1);
    $page_size = I("page_size", 10);    
    $name = trim(I("name"));
    $shop_name = trim(I("shop_name"));

    //上架
    $where = "s.app_id={$this->app_id} ";
    if ($name) {//用户名
      $where .= " and p.name like '%".trim($name)."%'";
      $where_ar['name']=$name;
      $this->assign("name", $name); 
    }

    if ($shop_name) {//店铺名
      $where .= " and s.name like '%".trim($shop_name)."%'";
      $where_ar['shop_name']=$shop_name;
      $this->assign("shop_name", $shop_name);
    }
    
    $field = "ms.*,p.name,p.status,s.name as shop_name,p.price,p.product_num,p.sales,p.hits";
    $order = "ms.id desc";
    $model = M('miaosha_products')->alias("ms")
        ->join("left join ".C("DB_PREFIX")."products p on p.id=ms.goods_id")
        ->join("left join ".C("DB_PREFIX")."shops s on p.shop_id=s.id")
        ->field($field)->where($where)->order($order);

    $list = $model->page($page.",".$page_size)->select();


    foreach($list as $k=>$v){ 
      $list[$k]['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
      $list[$k]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);

      $field = "id,price,name,stock";
      $spec_list = M("specs")->field($field)->where("product_id=".$v['goods_id'])->order("id asc")->select();

      $strs = ''; $price = 0;
      foreach ($spec_list as $key2 => $value2) {

        $price +=(int)$value2['stock'];
        $strs.="<tr><td>".$value2['name']."</td>";
        $strs.="<td>".$value2['price']."</td>";
        $strs.="<td>".$value2['stock']."</td></tr>";
      }
      if($strs){
        $list[$k]['product_num']= $price;
      }
      $list[$k]['spec'] = $strs;
    }
    $count = $model->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $count, $where_ar);
    $this->assign("page_list", $page_list);
    $this->display();
  }

  public function miaosha_delete()
  {
    $model = M("miaosha_products");
    $id = I("id");

    $data['is_delete'] = I("status", 1);;

    if(in_array($data['is_delete'],array(0,1)) && preg_match("/^[1-9][0-9]*$/",$id)){
      if ($model->where("id = $id")->save($data)) {
        $this->success('操作成功');
      } else {
        $this->error('操作失败');
      }
    }
  }

}
